package com.uroboros.spring.guides.rest.employee;

import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn;

import java.util.ArrayList;
import java.util.List;
import org.springframework.hateoas.CollectionModel;
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.server.RepresentationModelAssembler;
import org.springframework.stereotype.Component;

@Component
public class EmployeeModelAssembler implements RepresentationModelAssembler<Employee, EntityModel<Employee>> {

  @Override
  public EntityModel<Employee> toModel(Employee entity) {
    return EntityModel.of(entity,
        linkTo(methodOn(EmployeeController.class).oneByHypermediaDrivenSimplify(entity.getId())).withSelfRel(),
        linkTo(methodOn(EmployeeController.class).allByHypermediaDrivenSimplify()).withRel("employees"));
  }

  @Override
  public CollectionModel<EntityModel<Employee>> toCollectionModel(Iterable<? extends Employee> entities) {
    List<EntityModel<Employee>> employees = new ArrayList<>();
    entities.forEach(employee -> employees.add(toModel(employee)));

    return CollectionModel.of(employees, linkTo(methodOn(EmployeeController.class).allByHypermediaDrivenSimplify()).withSelfRel());
  }
}
